// /访客添加修改

import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom' //路由
import { RadioChangeEvent, Radio, Form, Input, Cascader, DatePicker, Upload, message, Button } from 'antd';
import "../../css/VisitorAdd.scss";
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';

import { cascade, upload2, addll } from "../../api/visitorList"; //接口

const VisitorList = () => {

  // 类型
  const [value, setValue] = useState(0);
  const onChange = (e: RadioChangeEvent) => {
    console.log('类型', e.target.value);
    setValue(e.target.value);
    setadd({
      ...add, type: e.target.value
    })
  };

  // 访客名称
  let username = (value: any) => {
    setadd({
      ...add, username: value.target.value
    })
  }

  // 手机号
  let cellPhone = (value: any) => {
    console.log(value.target.value);
    setadd({
      ...add, mobile: value.target.value
    })
  }

  // openid
  const [opid, setopid] = useState({ openid: '' })
  let openid = (value: any) => {
    console.log(value.target.value);
    setopid({
      ...opid, openid: value.target.value
    })
    setadd({
      ...add, openid: opid.openid
    })
  }

  // 身份证号
  const [card2, setcard] = useState({ identity2: '' })
  let identity = (value: any) => {
    // console.log(value.target.value);
    setcard({
      ...card2, identity2: value.target.value
    })
    // console.log(card2.identity2);
    
    setadd({
      ...add, card: card2.identity2
    })
  }

  // 车牌号
  const [carnumber2, setcarnumber] = useState({ carnumbe: '' })
  let carnumber = (value: any) => {
    setcarnumber({
      ...carnumber2, carnumbe: value.target.value
    })
    setadd({
      ...add, carnumber: carnumber2.carnumbe
    })
  }

  // 理由
  let reason = (value: any) => {
    setadd({
      ...add, reason: value.target.value
    })
  }

  // 部门级联
  const fieldNames = { label: 'name', value: 'id', children: 'son' }

  const [options, setoptions] = useState()

  // 掉接口
  let casCade2 = async () => {
    let res = await cascade()
    console.log(res);
    setoptions(res.data)
  }
  useEffect(() => {
    casCade2()
  }, [])

  let change = (id: any) => {
    // console.log(id);
    setadd({
      ...add, department: id
    })
  }

  // 进校时间
  let startime = (value: any, dateString: any) => {
    console.log(value, dateString);
    setadd({
      ...add, starttime: dateString
    })
  }

  // 出校时间
  let endtime = (value: any, dateString: any) => {
    console.log(value, dateString);
    setadd({
      ...add, endtime: dateString
    })
  }

  // 地区的数据
  const regionoptions = [
    {
      value: '山东',
      label: '山东',
      children: [
        {
          value: '菏泽',
          label: '菏泽',
          children: [
            {
              value: '曹县',
              label: '曹县',
            },
          ],
        },
      ],
    }
  ];

  // 点击获取地区
  let region = (value: any) => {
    console.log(value);
  }


  // 是否去过高风险地区
  const [value2, setValue2] = useState(0);
  const risk = (e: RadioChangeEvent) => {
    console.log('radio checked', e.target.value);
    setValue2(e.target.value);
  };

  // 是否接触过高风险地区
  const [value3, setValue3] = useState(0);
  const touchisk = (e: RadioChangeEvent) => {
    console.log('radio checked', e.target.value);
    setValue3(e.target.value);
  };


  // 健康状态
  const [value4, setValue4] = useState(0);
  const health = (e: RadioChangeEvent) => {
    console.log('radio checked', e.target.value);
    setValue4(e.target.value);
  };


  // 行程码
  let Authorization: any = sessionStorage.getItem('token')
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    console.log(info.fileList[0].response);

    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      let url = info.fileList[0].response.data.src
      // console.log(url);
      setImageUrl(url)
      setadd({
        ...add, travelcode: url
      })
    }
  };
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );


  // 疫苗--------------------------------------------------------
  const [loading2, setLoading2] = useState(false);
  const [imageUrl2, setImageUrl2] = useState<string>();
  const handleChange2: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    console.log(info);

    if (info.file.status === 'uploading') {
      setLoading2(true);
      return;
    }
    if (info.file.status === 'done') {
      let url = info.fileList[0].response.data.src
      setImageUrl2(url)
    }
  };
  const beforeUpload2 = (file: RcFile) => {
    const isJpgOrPng2 = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng2) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M2 = file.size / 1024 / 1024 < 2;
    if (!isLt2M2) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng2 && isLt2M2;
  };
  const uploadButton2 = (
    <div>
      {loading2 ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );


  // 健康码-------------------------------------
  const [loading3, setLoading3] = useState(false);
  const [imageUrl3, setImageUrl3] = useState<string>();
  const handleChange3: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    console.log(info);

    if (info.file.status === 'uploading') {
      setLoading2(true);
      return;
    }
    if (info.file.status === 'done') {
      let url = info.fileList[0].response.data.src
      setImageUrl3(url)
      setadd({
        ...add, healthcode: url
      })
    }
  };
  const beforeUpload3 = (file: RcFile) => {
    const isJpgOrPng3 = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng3) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M3 = file.size / 1024 / 1024 < 2;
    if (!isLt2M3) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng3 && isLt2M3;
  };
  const uploadButton3 = (
    <div>
      {loading3 ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );


  // 核酸-------------------------------------
  const [loading4, setLoading4] = useState(false);
  const [imageUrl4, setImageUrl4] = useState<string>();
  const handleChange4: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    console.log(info);

    if (info.file.status === 'uploading') {
      setLoading4(true);
      return;
    }
    if (info.file.status === 'done') {
      let url = info.fileList[0].response.data.src
      setImageUrl4(url)
      setadd({
        ...add, nucleicacid: url
      })
    }
  };
  const beforeUpload4 = (file: RcFile) => {
    const isJpgOrPng4 = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng4) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M4 = file.size / 1024 / 1024 < 2;
    if (!isLt2M4) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng4 && isLt2M4;
  };
  const uploadButton4 = (
    <div>
      {loading4 ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );


  // 点击添加
  const navigate = useNavigate() //路由
  // 添加需要的数据
  const [add, setadd]: any = useState({
    type: null,//来访类型 ：1 临时访问登记  2 在校生访问登记
    username: "", //名字
    mobile: "",//手机号
    card: "", //身份证
    carnumber: "鲁R888888",
    starttime: "", //进校时间
    endtime: "", //出校时间
    reason: "", //理由
    department: '',//部门
    travelcode: '',//行程码
    healthcode: '',//健康码
    nucleicacid: '', //核酸
    adduserid: sessionStorage.getItem('admin_id'),// 添加人id 在sessionStorage中获取（登录时存的用户信息）
    openid: ""
  })

  let addAll = async () => {
    console.log(add);
    add.department = add.department[add.department.length - 1] //截取到级联框最后一个值
    console.log(add.department);
    let res: any = await addll(add)
    console.log(res);
    if (res.code === '00000') {
      navigate('/index/VisitorList')
    }
  }



  return (<>
    <div className="vistoradd">

      {/* 左边 */}
      <div className='left'>
        <Form>

          {/* 类型 */}
          <Form.Item
            name="type"
            label="类型"
            rules={[
              {
                required: true,
                message: '请选择类型',
              },
            ]}>
            {/* 类型 */}
            <div>
              <Radio.Group onChange={onChange} value={value}>
                <Radio value={1}>外来人员</Radio>
                <Radio value={2}>老师</Radio>
                <Radio value={3}>学生</Radio>
              </Radio.Group>
            </div>
          </Form.Item>

          {/* 访客名称 */}
          <Form.Item
            name="username"
            label="访客名称"
            rules={[
              {
                required: true,
                message: '请输入访客名称',
              },
            ]}>
            <Input placeholder="请输入访客名称" value={value} onChange={username} />
          </Form.Item>

          {/* 手机号 */}
          <Form.Item
            name="mobile"
            label="手机号"
            rules={[
              {
                required: true,
                message: '请输入手机号',
              },
            ]}>
            <Input placeholder="请输入手机号" value={value} onChange={cellPhone} />
          </Form.Item>

          {/* openid */}
          <Form.Item label="openid">
            <Input placeholder="请输入openid" value={opid.openid} onChange={openid} />
          </Form.Item>

          {/* 身份证号 */}
          <Form.Item
            name="card"
            label="身份证号"
            rules={[
              {
                required: true,
                message: '请输入身份证号',
              },
            ]}>
            <Input placeholder="请输入身份证号" value={card2.identity2} onChange={identity} />
          </Form.Item>

          {/* 车牌号 */}
          <Form.Item label="车牌号">
            <Input placeholder="请输入车牌号" value={carnumber2.carnumbe} onChange={carnumber} />
          </Form.Item>

          {/* 理由 */}
          <Form.Item
            name="reason"
            label="理由"
            rules={[
              {
                required: true,
                message: '请输入理由',
              },
            ]}>
            <Input placeholder="请输入理由" value={value} onChange={reason} />
          </Form.Item>

          {/* 部门 */}
          <Form.Item
            name="department"
            label="部门"
          >
            <Cascader placeholder='请选择部门' fieldNames={fieldNames} options={options} onChange={change} />
          </Form.Item>

          {/* 进校时间 */}
          <Form.Item
            name="starttime"
            label="进校时间"
          >
            <DatePicker showTime className='select2' onChange={startime} />
          </Form.Item>

          {/* 出校时间 */}
          <Form.Item
            name="endtime"
            label="出校时间"
          >
            <DatePicker showTime className='select2' onChange={endtime} />
          </Form.Item>

          {/* 地区 */}
          <Form.Item
            label="地区"
          >
            <Cascader options={regionoptions} onChange={region} placeholder="请选择地址" />
          </Form.Item>

          {/* 是否去过高风险地区 */}
          <Form.Item
            label="是否去过高风险地区"
          >
            <Radio.Group onChange={risk} value={value2}>
              <Radio value={1}>是</Radio>
              <Radio value={2}>否</Radio>
            </Radio.Group>
          </Form.Item>

          {/* 是否接触过高风险地区 */}
          <Form.Item
            label="是否接触过高风险地区"
          >
            <Radio.Group onChange={touchisk} value={value3}>
              <Radio value={1}>是</Radio>
              <Radio value={2}>否</Radio>
            </Radio.Group>
          </Form.Item>

          {/* 将康状态 */}
          <Form.Item
            label="将康状态"
          >
            <Radio.Group onChange={health} value={value4}>
              <Radio value={1}>良好</Radio>
              <Radio value={2}>一般</Radio>
              <Radio value={3}>差</Radio>
            </Radio.Group>
          </Form.Item>

        </Form>
      </div>

      {/* 右边 */}
      <div className='right'>

        <div className='zuo'>

          {/* 行程码 */}
          <div className='xing'>
            <div className='xing2'>行程码：</div>
            <Upload
              name="file"
              headers={{ Authorization }}
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="http://121.42.230.80/api/visit/upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? < img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
            </Upload>
          </div>

          {/* 疫苗 */}
          <div className='xing'>
            <div className='xing2'>疫苗：</div>
            <Upload
              name="file"
              headers={{ Authorization }}
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="http://121.42.230.80/api/visit/upload"
              beforeUpload={beforeUpload2}
              onChange={handleChange2}
            >
              {imageUrl2 ? < img src={imageUrl2} alt="avatar" style={{ width: '100%' }} /> : uploadButton2}
            </Upload>
          </div>

        </div>

        <div className='zuo'>

          {/* 健康码 */}
          <div className='xing'>
            <div className='xing2'>健康码：</div>
            <Upload
              name="file"
              headers={{ Authorization }}
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="http://121.42.230.80/api/visit/upload"
              beforeUpload={beforeUpload3}
              onChange={handleChange3}
            >
              {imageUrl3 ? < img src={imageUrl3} alt="avatar" style={{ width: '100%' }} /> : uploadButton3}
            </Upload>
          </div>

          {/* 核酸 */}
          <div className='xing'>
            <div className='xing2'>核酸：</div>
            <Upload
              name="file"
              headers={{ Authorization }}
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="http://121.42.230.80/api/visit/upload"
              beforeUpload={beforeUpload4}
              onChange={handleChange4}
            >
              {imageUrl4 ? < img src={imageUrl4} alt="avatar" style={{ width: '100%' }} /> : uploadButton4}
            </Upload>
          </div>

        </div>

        <div className='addition'>
          <Button type="primary" onClick={addAll}>添加</Button>
        </div>

      </div>

    </div>
  </>);

}

export default VisitorList;